<?php

class Model_Assignment extends Zend_Db_Table_Abstract
{
   	protected $_table;
	protected $paper;
	protected $participant;
    public function getTable()
    {
        if (null === $this->_table) {            
            require_once APPLICATION_PATH . '/models/DbTable/Assignment.php';
            $this->_table = new Model_DbTable_Assignment;
        }
        return $this->_table;
    }
   
    public function save(array $data)
    {
    		if(isset($data['id'])){
    			$id = $data['id'];
    		}else{
    			$id = 0;
    		}
    		
        $table  = $this->getTable();
        $fields = $table->info(Zend_Db_Table_Abstract::COLS);        
        foreach ($data as $field => $value) {
            if (!in_array($field, $fields)) {
                unset($data[$field]);                
            }
            
        }
        
        if($id == 0){
        	return $table->insert($data);
        }else{
        	$where = $table->getAdapter()->quoteInto('id = ?', $id);
        	return $table->update($data, $where);
        }
    }
	public function assignPapers($reviewers, $papers){
		$r_count = count($reviewers);
		$p_count = count($papers);
		$assigned = array();
		for($i = 0; $i < $r_count; $i++){
			for($j = 0; $j < $p_count; $j++){
				$can = $this->canAssign($papers[$j], $reviewers[$i]);
				if($can){
					$data = array();
					$data['paper_id'] = $papers[$j];
					$data['reviewer_id'] = $reviewers[$i];
					$data['isActive'] = 1;
					$data['date_assigned'] = date('Y-m-d H:i:s');
					$data['isNotified'] = 0;
					//TODO notify by email
					$this->save($data);
					$assigned[$papers[$j]] = true;
				}
			}
		}
		return $assigned;			
	}
	
	public function reassignPapers($reviewers, $papers){
		$r_count = count($reviewers);
		$p_count = count($papers);
        $assigned = array();
		for($i = 0; $i < $r_count; $i++){
			for($j = 0; $j < $p_count; $j++){
				$can = $this->canAssign($papers[$j], $reviewers[$i]);
				if($can){
					$data = array();
					$data['paper_id'] = $papers[$j];
					$data['reviewer_id'] = $reviewers[$i];
					$data['isActive'] = 1;
					$data['date_assigned'] = date('Y-m-d H:i:s');
					$data['isNotified'] = 0;
					//TODO notify by email
					$this->save($data);
                    $assigned[$papers[$j]] = true;
				}
			}
		}
        return $assigned;        
	}
	function cancelAssignment($papers){
        $table  = $this->getTable();
        $data['isActive'] = 0;
        foreach($papers as $p){            
            $where = $table->getAdapter()->quoteInto('paper_id = ?', $p);
            $table->update($data, $where);            
        }        
    }
	function cancelAssignments($assignments){
        $table  = $this->getTable();
        $data['isActive'] = 0;
        foreach($assignments as $a){            
            $where = $table->getAdapter()->quoteInto('id = ?', $a);
            $table->update($data, $where);            
        }        
    }
	function notifyAssignments($assignments){
        $table  = $this->getTable();
        $data['isNotified'] = 1;
		$reviewers = array();
		$i = 0;
		$p = $this->getParticipant();
        foreach($assignments as $a){            
            $where = $table->getAdapter()->quoteInto('id = ?', $a);
            $table->update($data, $where);            
        }        
    }
    public function getAssignments($sort, $dir, $filter){
    	$table = $this->getTable();
      	$db = $table->getAdapter();			
		$select = $db->select()->from(array('a' => 'assignments'), 
		array('id', 'reviewer_id', 'paper_id', 'date_assigned', 'date_downloaded', 'isNotified', 'isActive'))
							 ->join(array('p' => 'papers'), 'p.id = a.paper_id', array('title'))
                             ->join(array('pt' => 'participants'), 'pt.id = a.reviewer_id', array('first_name', 'last_name', 'email'))                                                          
              			->where('a.isActive = 1');
        if(isset($filter)){
            foreach($filter as $f){
                $q = $f['field'] . ' LIKE ?'; 
                $v = '%' . $f['data']['value'] . '%';                
                $select->where($q, $v);
            }
        }
		$select->order($sort . ' ' . $dir);
		$stmt = $select->query();			
      	return $stmt->fetchAll();
    }
	public function getAssignments1($sort, $dir){
	  	$table = $this->getTable();		 			
		$db = $table->getAdapter();			
		$sql = 'SELECT a.id, a.reviewer_id, a.paper_id, a.date_assigned, a.date_downloaded, a.isNotified, a.isActive,
				p.title, CONCAT(pt.first_name, " ", pt.last_name) as reviewer, pt.email,
				(SELECT COUNT(r.id) FROM reviews r WHERE r.assignment_id = a.id) as reviews_count
				FROM assignments a
				JOIN papers p ON p.id = a.paper_id
				JOIN participants pt ON pt.id = a.reviewer_id
				WHERE a.isActive = 1
				ORDER BY ' . $sort . ' ' . $dir;
		$res = $db->query($sql);    			
      	return $res->fetchAll();
    }
    function fetchEntries()
    {       
        return $this->getTable()->fetchAll('1')->toArray();
    }
   
    public function fetchEntry($id)
    {
        $table = $this->getTable();
        $select = $table->select()->where('id = ?', $id);    
        return $table->fetchRow($select);
    }
	private function canAssign($paper_id, $participant_id){
		$paper = $this->getPaper();
		$can = $paper->canAssign($paper_id, $participant_id);
		return $can == 0;
	}
	private function getPaper(){
		if($this->paper === null){
			require_once APPLICATION_PATH . '/models/Paper.php';
    		$this->paper = new Model_Paper();
		}
		return $this->paper;
	}	  
	private function getParticipant(){
		if($this->participant === null){
			require_once APPLICATION_PATH . '/models/Participant.php';
    		$this->participant = new Model_Participant();
		}
		return $this->participant;
	}	  
}